// pages2/pages/mall/selectLocation/index.js
import { debounce, getLatLng, initLocationPersmiss } from '../../../../utils/util';
const $api = require('../../../../request/api').API;
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    recentSearchRegion: [],
    hotRegion: ['长沙市', '上海市', '北京市', '重庆市', '深圳市', '岳阳市'],
    indexList: [
      '最近热门',
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'I',
      'J',
      'K',
      'L',
      'M',
      'N',
      'O',
      'P',
      'Q',
      'R',
      'S',
      'T',
      'U',
      'V',
      'W',
      'X',
      'Y',
      'Z'
    ],
    regionList: [],
    resultList: [],
    keyWord: '',
    addressName: '', //当前位置名称
    address: '', //城市或者区县
    //经纬度
    latitude: '',
    longitude: '',
    province: '', //当前省
    city: '', //当前城市
    cityRegionList: [] //当前市下的区县列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.address) {
      this.setData({
        address: options.address,
        province: options.province
      });
      // 通过地址解析出当前市,然后通过当前市来获取该市下面的区县
      this.getCurrentCityRegion();
    }

    let region = wx.getStorageSync('region');
    if (region) {
      this.setData({
        recentSearchRegion: JSON.parse(region)
      });
    }

    this.getRegion();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  // 获取市区县并格式化
  getRegion() {
    $api.regionData().then(res => {
      let obj = [];
      let data = res.data.data;
      for (let item in data) {
        obj.push({ title: item, cities: data[item] });
      }
      this.setData({
        regionList: obj
      });
    });
  },
  // 搜索输入
  inputKey: debounce(function (e) {
    this.setData({
      keyWord: e.detail.value
    });
    $api.regionData({ name: this.data.keyWord, type: 1 }).then(res => {
      this.setData({
        resultList: res.data ? res.data.data.one : []
      });
    });
  }, 500),
  onChange(e) {
    this.setData({
      active: e.detail.index
    });
  },
  // 获取定位位置并去商城
  getMyLocation() {
    initLocationPersmiss().then(res => {
      app.globalData.address = res.address_component.city;
      app.globalData.provinceName = res.address_component.province;
      app.globalData.cityName = res.address_component.city;
      app.globalData.areaName = res.address_component.district;
      app.globalData.latitude = res.location.lat;
      app.globalData.longitude = res.location.lng;
      let region = [];
      let city = res.address_component.city;
      region = JSON.parse(wx.getStorageSync('region'));
      if (wx.getStorageSync('region')) {
        // 本地有最近访问的地址
        if (region.findIndex(item => item == city) == -1) {
          // 最近访问的地址里面有当前城市
          if (region.length < 4) {
            // 最近访问的城市数量大于4
            region.push(city);
          } else {
            region.splice(0, 1, city);
          }
          wx.setStorageSync('region', JSON.stringify(region));
        }
      } else {
        region.push(city);
        wx.setStorageSync('region', JSON.stringify(region));
      }
      wx.navigateBack({
        delta: 1
      });
      // wx.switchTab({
      //     url: '../../../../pages/home/index',
      //   })
    });
  },
  // 获取当前城市下面的区县
  getCurrentCityRegion() {
    getLatLng(this.data.province + this.data.address).then(res => {
      this.setData({
        city: res.address_components.city
      });
      // 通过市获取当前市下的所有区县
      $api.regionData({ name: this.data.city, type: 2 }).then(res => {
        let data = res.data.data;
        if (data) {
          this.setData({
            cityRegionList: Object.values(data)[0]
          });
          // this.setData({
          //     cityRegionList:data[this.data.city].map(item=>({parentName:this.data.city,areaName:item.areaName}))
          // })
        }
      });
    });
  },
  // 去商城
  toBtnList(e) {
    let item = e.currentTarget.dataset.item || e.target.dataset.item;
    if (!item) return;
    let addAddress = null;
    let address = null;
    if (typeof item == 'string') {
      addAddress = item;
      address = item;
    } else {
      addAddress = item.parentName ? item.parentName + item.areaName : item.areaName;
      address = item.areaName;
    }
    if (!addAddress) return;
    getLatLng(addAddress).then(res => {
      this.setData({
        latitude: res.location.lat,
        longitude: res.location.lng
      });
      let region = [];
      let city = res.address_components.city;
      if (wx.getStorageSync('region')) {
        // 本地有最近访问的地址
        region = JSON.parse(wx.getStorageSync('region'));
        if (region.findIndex(item => item == city) == -1) {
          // 最近访问的地址里面有当前城市
          if (region.length < 4) {
            // 最近访问的城市数量大于4
            region.push(city);
          } else {
            region.splice(0, 1, city);
          }
          wx.setStorageSync('region', JSON.stringify(region));
        }
      } else {
        region.push(city);
        wx.setStorageSync('region', JSON.stringify(region));
      }

      app.globalData.address = address;
      app.globalData.latitude = res.location.lat;
      app.globalData.longitude = res.location.lng;
      app.globalData.provinceName = res.address_components.province;
      app.globalData.cityName = city;
      app.globalData.areaName = res.address_components.district;
      wx.navigateBack({
        delta: 1
      });
      // wx.switchTab({
      //   url: '../../../../pages/home/index',
      // })
    });
  },
  // 点击获取经纬度

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});
